package friendsearch;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GeoInfo {

	List <GeoLocation> loc=new ArrayList <GeoLocation>();
	
	static GeoInfo geoInfo=new GeoInfo();
	
	private GeoInfo() {
		pre(Config.dataFileName);
	}
	
	public static GeoInfo getInstance() {
		return geoInfo;
	}
	
	public GeoLocation search(String province,String city) {
		 GeoLocation gl=null;
		 Iterator<GeoLocation> it=loc.iterator();
		 while(it.hasNext()) {
			 gl=it.next();
			 if(gl.getProvince().equals(province) && gl.getCity().equals(city))
				 return gl;
		 }
		 return null;
	}
	
	private void pre(String rawfilename) {
		File f=new File(rawfilename);
		if(f.exists()) {
			BufferedReader br=null;
			GeoLocation gl=null;
			Coordinate c=null;
			try {
				String line;
				InputStreamReader read = new InputStreamReader(new FileInputStream(f),"utf-8"); 
				br=new BufferedReader(read);
				while((line=br.readLine())!=null) {
					if(line.trim().length()==0) continue;
					String words[]=line.split("[ .]");
					
//					for(int i=0;i<words.length;i++) {
//						System.out.println(words[i]);
//					}
					
					gl=new GeoLocation();
					gl.setProvince(words[0]);
					gl.setCity(words[1]);
					double latitude=0;
					latitude=Double.parseDouble(words[2])+Double.parseDouble(words[3])/60;
					double longitude=0;
					longitude=Double.parseDouble(words[4])+Double.parseDouble(words[5])/60;
					c=new Coordinate(longitude,latitude);
					gl.setCoordinate(c);
					loc.add(gl);
				}
				br.close();
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
		else {
			System.out.println(rawfilename+" does not exist");
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String province="山东省";
		String city="烟台";
		System.out.println(GeoInfo.getInstance().search(province, city));
	}

}
